//
//  AuthenMiniVC.swift
//  kxf
//
//  Created by Mac on 2024/3/6.
//

import Foundation
import MCToast


class AuthenMiniVC: WHBaseViewVC {
    
    var type = "merc"
    
    //是否为被驳回后的资料修改
    var isUpdate = false
    //是否为只读模式
    var isRead = false
    //是否为代理商帮忙填写信息
    var isAgentEdit = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        initUI()
        
        if isUpdate {
            mercMsgVm.updateUIForRefuse()
            legalMsgVm.updateUIForRefuse()
        }
        if isRead{
            mercMsgVm.setReadMode()
            legalMsgVm.setReadMode()
            saveBtn.isHidden = true
            legalMsgVm.nextBtn.isHidden = true
        }
    }
    lazy var saveBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        
        btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var typeVm : AuthenTopTypeMiniVM = {
        let vm = AuthenTopTypeMiniVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        vm.typeChangeBlock = {(type)in
            self.type = type
            if type == "merc"{
                self.mercMsgVm.isHidden = false
                self.legalMsgVm.isHidden = true
            }else{
                self.mercMsgVm.isHidden = true
                self.legalMsgVm.isHidden = false
            }
        }
        return vm
    }()
    lazy var mercMsgVm : AuthenMiniMercVM = {
        let vm = AuthenMiniMercVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.typeVm.frame.maxY+kFitWidth(10))))
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.nextBlock = {()in
            self.saveAction()
            self.nextAction()
        }
        vm.msgVm.areaCodeVm.tapBlock = {()in
            self.sendProvinceRequest()
        }
        return vm
    }()
    lazy var legalMsgVm : AuthenMiniLegalVM = {
        let vm = AuthenMiniLegalVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.typeVm.frame.maxY+kFitWidth(10))))
        vm.isHidden = true
        vm.photoVm.controller = self
        vm.msgVm.controller = self
        vm.nextBlock = {()in
            self.nextAction()
        }
        return vm
    }()
    lazy var addressPickerVm : AddressPickerVM = {
        let vm = AddressPickerVM.init(frame: .zero)
        vm.isHidden = true
        
        vm.tapBlock = {(dict)in
            if self.addressPickerVm.regionType == .province{
                AddressModel.shareInstance.addressProvinceCode = dict["regionCode"]as? String ?? ""
                AddressModel.shareInstance.addressProvinceName = dict["regionName"]as? String ?? ""
                self.sendCityRequest()
            }else if self.addressPickerVm.regionType == .city{
                AddressModel.shareInstance.addressCityCode = dict["regionCode"]as? String ?? ""
                AddressModel.shareInstance.addressCityName = dict["regionName"]as? String ?? ""
                self.sendAreaRequest()
            }else if self.addressPickerVm.regionType == .area{
                AddressModel.shareInstance.addressAreaCode = dict["regionCode"]as? String ?? ""
                AddressModel.shareInstance.addressAreaName = dict["regionName"]as? String ?? ""
                
                self.mercMsgVm.msgVm.areaCodeVm.setLabelContent(content: "\(AddressModel.shareInstance.addressProvinceName)\(AddressModel.shareInstance.addressCityName)\(AddressModel.shareInstance.addressAreaName)")
                AuthenMiniMsgModel.shareInstance.dealAddressToPlaceCode()
            }
        }
        vm.cancelBlock = {()in
            AddressModel.shareInstance.clearAddressMsg()
        }
        return vm
    }()
}

extension AuthenMiniVC{
    @objc func saveAction() {
        mercMsgVm.msgVm.getValue()
        legalMsgVm.getValue()
        sendSaveMsgRequest(isSubmit:false)
    }
    @objc func nextAction() {
        if self.type == "merc"{
            if self.isRead {
                self.type = "legal"
                self.typeVm.type = "legal"
                self.mercMsgVm.isHidden = true
                self.legalMsgVm.isHidden = false
                self.typeVm.merchantMsgVM.setSelected(isSelect: false)
                self.typeVm.legalMsgVm.setSelected(isSelect: true)
                self.sendSaveMsgRequest(isSubmit:false)
            }else if mercMsgVm.checkValue(){
                self.type = "legal"
                self.typeVm.type = "legal"
                self.mercMsgVm.isHidden = true
                self.legalMsgVm.isHidden = false
                self.typeVm.merchantMsgVM.setSelected(isSelect: false)
                self.typeVm.legalMsgVm.setSelected(isSelect: true)
            }
        }else{
            if self.isRead {
                
            }else if mercMsgVm.checkValue() && legalMsgVm.checkValue(){
                self.sendSaveMsgRequest(isSubmit:true)
            }
        }
    }
    func initUI() {
        initNavi(titleStr: "小微商户进件")
        self.navigationView.addSubview(self.saveBtn)
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.addSubview(typeVm)
        view.addSubview(mercMsgVm)
        view.addSubview(legalMsgVm)
        
        UIApplication.shared.keyWindow?.addSubview(addressPickerVm)
        
        setConstrait()
    }
    func setConstrait() {
        saveBtn.snp.makeConstraints { make in
            make.centerY.lessThanOrEqualTo(self.naviTitleLabel)
            make.right.equalToSuperview()
            make.width.equalTo(kFitWidth(72))
            make.height.equalTo(kFitWidth(20))
        }
    }
}

extension AuthenMiniVC{
    func sendSaveMsgRequest(isSubmit:Bool) {
        let param = AuthenMsgParam.shared.paramsForMiniMercMsg()
//        if !judgePhoneNumber(phoneNum: (param["tel"]as? String ?? "")){
//            self.presentAlertVcNoAction(title: "请输入正确的手机号", viewController: self)
//            return
//        }
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_msg_save, parameters: param as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200{
                if isSubmit{
                    if UserModel.shared.posChannel == "fy" && self.isAgentEdit {
                        let vc = AuthenSetRateVC()
                        vc.phone = AuthenMiniMsgModel.shareInstance.tel
                        vc.param = param
                        self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        self.sendCertRequest(param: param)
                    }
                }else{
                    MCToast.mc_text("信息保存成功")
                }
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "保存失败!")", viewController: self)
            }
        }
    }
    //入网
    func sendCertRequest(param:NSDictionary) {
        MCToast.mc_loading()
        let paramDict = NSMutableDictionary.init(dictionary: param)
        paramDict.setValue("0", forKey: "type")
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_user_cert, parameters: paramDict as? [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            if responseObject["code"]as? Int ?? 0 == 200{
                AuthenMiniMsgModel.shareInstance.clearMsg()
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "提交成功，请等待审核。", cancelBtn: nil, handler: { action in
                    self.navigationController?.popToRootViewController(animated: true)
                }, viewController: self)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "保存失败!")", viewController: self)
            }
        }
    }
    func sendProvinceRequest() {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().POST(urlString: URL_address_province, parameters: nil) { responseObject in
            DLLog(message: "sendProvinceRequest:\(responseObject)")
            
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.cancelBtn.isHidden = true
            self.addressPickerVm.regionType = .province
        }
    }
    func sendCityRequest() {
        MCToast.mc_loading()
        let param:[String : String] = ["provinceCode":"\(AddressModel.shareInstance.addressProvinceCode)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_address_city, parameters: param as [String : AnyObject]) { responseObject in
            DLLog(message: "sendCityRequest:\(responseObject)")
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.regionType = .city
            self.addressPickerVm.cancelBtn.isHidden = false
        }
    }
    func sendAreaRequest() {
        MCToast.mc_loading()
        let param = ["cityCode":"\(AddressModel.shareInstance.addressCityCode)"]
        WHNetworkUtil.shareManager().POST(urlString: URL_address_area, parameters: param as [String : AnyObject]) { responseObject in
            DLLog(message: "sendAreaRequest:\(responseObject)")
            let dataArr = responseObject["data"]as? NSArray ?? []
            self.addressPickerVm.setDataSource(dataArray: dataArr)
            self.addressPickerVm.cancelBtn.isHidden = false
            self.addressPickerVm.regionType = .area
        }
    }
}
